﻿using System.Drawing.Imaging;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Itour.Models;
using System;
using CustomerAssistant.Core;

namespace CustomerAssistant
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : UserControl
    {
        static readonly string EncryKey = "ca@itour";
        public static OperatorLoginData OperatorLoginData = null;
        bool IsMouseDown = false;
        Point mousePoint;
        EventWaitHandle ARE = new AutoResetEvent(false);

        public Login()
        {
            InitializeComponent();
            myInitializeComponent();
        }

        private void myInitializeComponent()
        {
            var mainbgBrush = this.Background as ImageBrush;
            this.Width = mainbgBrush.ImageSource.Width;
            this.Height = mainbgBrush.ImageSource.Height;
            this.image1.Width = this.image1.Source.Width;
            this.image1.Height = this.image1.Source.Height;
            this.image1.MouseMove += new MouseEventHandler((obj, arg) =>
            {
                this.image1.Source = SysHelper.GetImageSource(Properties.Resource.ninimize_hover, ImageFormat.Png);
                this.image1.Width = this.image1.Source.Width;
                this.image1.Height = this.image1.Source.Height;
                this.image1.Margin = new Thickness()
                {
                    Top = 0
                    ,
                    Right = 0
                    ,
                    Left = this.Width - this.image1.Width - this.image2.Width
                    ,
                    Bottom = this.Height - this.image1.Height
                };
            });
            this.image1.MouseLeave += new MouseEventHandler((obj, arg) =>
            {
                this.image1.Source = SysHelper.GetImageSource(Properties.Resource.ninimize, ImageFormat.Png);
                this.image1.Width = this.image1.Source.Width;
                this.image1.Height = this.image1.Source.Height;
                this.image1.Margin = new Thickness()
                {
                    Top = 0
                    ,
                    Right = 0
                    ,
                    Left = this.Width - this.image1.Width - this.image2.Width
                    ,
                    Bottom = this.Height - this.image1.Height
                };
            });
            this.image2.Width = this.image2.Source.Width;
            this.image2.Height = this.image2.Source.Height;
            this.image2.MouseMove += new MouseEventHandler((obj, arg) =>
            {
                this.image2.Source = SysHelper.GetImageSource(Properties.Resource.delete_hover, ImageFormat.Png);
                this.image2.Width = this.image2.Source.Width;
                this.image2.Height = this.image2.Source.Height;
                this.image2.Margin = new Thickness()
                {
                    Top = 0
                    ,
                    Right = 0
                    ,
                    Left = this.Width - this.image2.Width
                    ,
                    Bottom = this.Height - this.image2.Height
                };
            });
            this.image2.MouseLeave += new MouseEventHandler((obj, arg) =>
            {
                this.image2.Source = SysHelper.GetImageSource(Properties.Resource.delete, ImageFormat.Png);
                this.image2.Width = this.image2.Source.Width;
                this.image2.Height = this.image2.Source.Height;
                this.image2.Margin = new Thickness()
                {
                    Top = 0
                    ,
                    Right = 0
                    ,
                    Left = this.Width - this.image2.Width
                    ,
                    Bottom = this.Height - this.image2.Height
                };
            });
            this.image1.Margin = new Thickness()
            {
                Top = 0
                ,
                Right = 0
                ,
                Left = this.Width - this.image1.Width - this.image2.Width
                ,
                Bottom = this.Height - this.image1.Height
            };
            this.image2.Margin = new Thickness()
            {
                Top = 0
                ,
                Right = 0
                ,
                Left = this.Width - this.image2.Width
                ,
                Bottom = this.Height - this.image2.Height
            };
            this.image3.Width = this.image3.Source.Width;
            this.image3.Height = this.image3.Source.Height;
            this.image3.Margin = new Thickness()
            {
                Top = 29
                ,
                Right = (this.Width - this.image3.Width) / 2
                ,
                Left = (this.Width - this.image3.Width) / 2
                ,
                Bottom = this.Height - this.image3.Height - this.image3.Margin.Top
            };
            this.passwordBox1.Width = this.textBox1.Width = 182;
            this.passwordBox1.Height = this.textBox1.Height = 25;
            this.textBox1.BorderThickness = new Thickness(0);
            this.passwordBox1.BorderThickness = new Thickness(0);
            this.image4.Width = this.image4.Source.Width;
            this.image4.Height = this.image4.Source.Height;
            this.image4.Margin = new Thickness()
            {
                Top = 215,
                Right = (this.Width - this.image4.Width) / 2
                ,
                Left = (this.Width - this.image4.Width) / 2
            };
            this.image4.MouseMove += new MouseEventHandler((obj, arg) =>
            {
                this.image4.Source = SysHelper.GetImageSource(Properties.Resource.login_btn_hover, ImageFormat.Png);
                this.image4.Width = this.image4.Source.Width;
                this.image4.Height = this.image4.Source.Height;
            });
            this.image4.MouseLeave += new MouseEventHandler((obj, arg) =>
            {
                this.image4.Source = SysHelper.GetImageSource(Properties.Resource.login_btn, ImageFormat.Png);
                this.image4.Width = this.image4.Source.Width;
                this.image4.Height = this.image4.Source.Height;
            });
        }

        private void canvas1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                IsMouseDown = true;
                mousePoint = e.GetPosition(this);
            }
        }

        private void canvas1_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (IsMouseDown)
            {
                IsMouseDown = false;
            }
        }

        private void canvas1_MouseMove(object sender, MouseEventArgs e)
        {
            if (IsMouseDown)
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    var popup = Parent as Window;
                    Point mousePoint2 = e.GetPosition(this);
                    var h = popup.Left - (mousePoint.X - mousePoint2.X);

                    var v = popup.Top - (mousePoint.Y - mousePoint2.Y);

                    if (h <= (SystemParameters.PrimaryScreenWidth - this.Width) && h >= 0)
                        popup.Left = h;
                    else
                        mousePoint.X = mousePoint2.X;
                    if (v <= (SystemParameters.PrimaryScreenHeight - this.Height) && v >= 0)
                        popup.Top = v;
                    else
                        mousePoint.Y = mousePoint2.Y;
                }
            }
        }

        private void image2_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void image1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            (this.Parent as Window).WindowState = WindowState.Minimized;
        }

        private void image4_MouseDown(object sender, MouseButtonEventArgs e)
        {
            myLogin();
        }

        public void AutoLogin()
        {
            if (this.checkBox2.IsChecked == true)
            {
                myLogin();
            }
        }

        private void myLogin()
        {
            var name = textBox1.Text;
            var pwd = passwordBox1.Password;
            var url = Properties.Settings.Default.serviceUrl;
            var xml = string.Empty;
            try
            {
                CustomerAssistant.Core.Util.HttpRequest(url, string.Format("handle=login&oname={0}&pwd={1}", name, pwd), (data) =>
                    {
                        xml = data;
                        ARE.Set();
                    });
            }
            catch (System.Net.WebException e)
            {
                if (e.Status == System.Net.WebExceptionStatus.Timeout)
                {
                    var tip = new InfoTip();
                    var wnd = new Window();
                    wnd.Icon = SysHelper.GetImageSource(Properties.Resource.info1, ImageFormat.Png);
                    wnd.Title = "登录提示";
                    var txtTip = new textTip();
                    txtTip.textBlock1.Text = "登录失败,连接服务器超时!";
                    txtTip.Margin = new Thickness(15, 50, 0, 0);
                    tip.grid1.Children.Add(txtTip);
                    tip.Height = 158;
                    TrayNotifyUtil.ShowInfoTip(wnd, tip, "SC");
                    //登录失败
                    return;
                }
            }
            this.Dispatcher.BeginInvoke(new Action(() => 
            {
                ARE.WaitOne();
                if (string.IsNullOrEmpty(xml))
                {
                    var tip = new InfoTip();
                    var wnd = new Window();
                    wnd.Icon = SysHelper.GetImageSource(Properties.Resource.info1, ImageFormat.Png);
                    wnd.Title = "登录提示";
                    var txtTip = new textTip();
                    txtTip.textBlock1.Text = "登录失败,请确认账户与密码是否正确!";
                    txtTip.Margin = new Thickness(15, 50, 0, 0);
                    tip.grid1.Children.Add(txtTip);
                    tip.Height = 158;
                    TrayNotifyUtil.ShowInfoTip(wnd, tip, "SC");
                    //登录失败
                    return;
                }
                OperatorLoginData = CustomerAssistant.Core.Util.Deserialize<Itour.Models.OperatorLoginData>(xml);
                if (OperatorLoginData == null)
                {
                    LogHelper.LogError("从服务端返回的xml无法反序列化为对象.");
                }
                if (checkBox1.IsChecked == true)
                {
                    RememberUser();
                }
                else
                {
                    Properties.Settings.Default.NameEncryptText = string.Empty;
                    Properties.Settings.Default.PwdEncryptText = string.Empty;
                }
                Properties.Settings.Default.AutoLogin = checkBox2.IsChecked != null && (bool)checkBox2.IsChecked;
                Properties.Settings.Default.Save();
                (this.Parent as Window).Close();
                OrderMonitor.CreateNotice();
                Thread thread1 = new Thread(() =>
                {
                    OrderMonitor.Run();
                });
                thread1.IsBackground = true;
                thread1.Start();
            }));
        }

        /// <summary>
        /// 记住密码
        /// </summary>
        private void RememberUser()
        {
            var name = textBox1.Text;
            var pwd = passwordBox1.Password;
            Properties.Settings.Default.NameEncryptText = Util.Encrypt(name, EncryKey);
            Properties.Settings.Default.PwdEncryptText = Util.Encrypt(pwd, EncryKey);
            Properties.Settings.Default.Save();
        }

        public void SettingInit()
        {
            try
            {
                this.textBox1.Text = Util.Decrypt(Properties.Settings.Default.NameEncryptText, EncryKey);
                this.passwordBox1.Password = Util.Decrypt(Properties.Settings.Default.PwdEncryptText, EncryKey);
                this.checkBox1.IsChecked =
                    (!string.IsNullOrEmpty(Properties.Settings.Default.NameEncryptText)) &&
                    (!string.IsNullOrEmpty(Properties.Settings.Default.PwdEncryptText));
                this.checkBox2.IsChecked = Properties.Settings.Default.AutoLogin && this.checkBox1.IsChecked == true;
            }
            catch
            {
                Properties.Settings.Default.NameEncryptText = null;
                Properties.Settings.Default.PwdEncryptText = null;
                Properties.Settings.Default.Save();
            }
        }
    }
}